/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cbsnserverparte;

import java.io.*;

/**
 *
 * @author Craig Butler (5668670)
 * @author Stephen Norman (616000X)
 */
final class Writer
{
    // The output stream to write to
    static DataOutputStream writer;
    
    static void writePacket(int seqNum, byte[] data)
    {
        try       
        {
            // Write the packet to the output stream
            int packetSize = 0;
            
            // Get the hash of the packetData
            byte[] hash = Util.hashPacket(data).getBytes();
            
            // Leave a blank line
            System.out.println();
            
            // Some dashes
            System.out.println("---------------------------------------------------");
            
            // Print out what is been sent
            System.out.println(Util.getTime() + "Transmitting packet (contents below)");
            
            // Leave a blank line
            System.out.println();
            
            System.out.println("Sequence Number : " + seqNum);
            System.out.println("MD5 Hash        : " + new String(hash));
            System.out.println("Data Length     : " + data.length + " bytes");
            
            // Leave a blank line
            System.out.println();
            
            // Write the sequence number of the packet
            writer.writeInt(seqNum);
            packetSize += 4;
            
            // Write the hash
            writer.write(hash, 0, hash.length);
            packetSize += hash.length;
            
            // Write the data length
            writer.writeInt(data.length);
            packetSize += 4;
            
            // Write the data
            writer.write(data, 0, data.length);
            packetSize += data.length;
            
            // We need to pad out the packet up to 1460
            int remaining = 1460 - packetSize;           
            byte[] padding;
            
            if (remaining > 0)
            {
                 padding = new byte[remaining];
                 writer.write(padding);
            }                      
        }
        catch (Exception ex)
        {
            System.out.println(Util.getTime() + "Write Error: " + ex.getMessage());
            System.exit(1);
        }
    }
}
